<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card style="margin-top: 20px;">
      <el-button
        style="margin:10px 0;"
        type="primary"
        @click="addclassification"
        >添加分类</el-button
      >
      <tree-table
        :data="cateList"
        :columns="columns"
        :selection-type="false"
        :expand-type="false"
        show-index
        index-text="#"
        border
        :show-row-hover="false"
      >
        <template slot="one" scope="scope">
          <i
            v-if="scope.row.cat_deleted == false"
            class="el-icon-success"
            style="color: green;"
          ></i>
          <i v-else class="el-icon-success"></i>
        </template>
        <template slot="two" scope="scope">
          <el-tag v-if="scope.row.cat_level == 0">一级</el-tag>
          <el-tag v-else-if="scope.row.cat_level == 1" type="success"
            >二级</el-tag
          >
          <el-tag v-else type="warning">三级</el-tag>
        </template>
        <template slot="three" scope="scope">
          <el-button
            type="primary"
            icon="el-icon-edit"
            size="mini"
            @click="editCate(scope.row)"
            >编辑</el-button
          >
          <el-button
            type="danger"
            icon="el-icon-delete"
            size="mini"
            @click="delCate(scope.row)"
            >删除</el-button
          >
        </template>
      </tree-table>
    </el-card>
    <!-- 添加弹框 -->
    <el-dialog
      title="添加分类"
      :visible.sync="dialogVisible"
      width="30%"
      @close="addCateDialogClosed"
    >
      <el-form
        :model="classificationForm"
        :rules="addCateFormRules"
        ref="classificationForm"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="父类名称" prop="cat_name">
          <el-input v-model="classificationForm.cat_name"></el-input>
        </el-form-item>
        <el-form-item label="父级分类">
          <div class="block">
            <el-cascader
              expandTrigger="hover"
              v-model="selectedKeys"
              :options="parentCateList"
              :props="cascaderProps"
              @change="parentCateChange"
              clearable
              change-on-select
            ></el-cascader>
          </div>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addCate">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 分页器 -->
    <div class="block">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="cateInfo.pagenum"
        :page-sizes="[3, 6, 8, 10]"
        :page-size="cateInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </div>
    <!-- 编辑弹框 -->
    <el-dialog title="编辑分类" :visible.sync="editdialogVisible" width="30%">
      <el-form
        :model="editForm"
        :rules="addCateFormRules"
        ref="editForm"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="父类名称" prop="cat_name">
          <el-input v-model="editForm.cat_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editdialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editCatr1(editForm.cat_id)"
          >确 定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: "",
  // 组件注册
  components: {},
  // 父组件传参
  props: {},
  // 变量声明
  data() {
    return {
      editdialogVisible: false, // 控制编辑弹框显示隐藏
      cateList: [],
      cateInfo: {
        type: 3,
        pagenum: 1,
        pagesize: 10,
      },
      total: 0, //总条数
      columns: [
        { label: "分类名称", prop: "cat_name" },
        { label: "是否有效", prop: "", type: "template", template: "one" },
        { label: "排序", prop: "", type: "template", template: "two" },
        { label: "操作", prop: "", type: "template", template: "three" },
      ],
      dialogVisible: false, //控制添加弹框显示隐藏
      classificationForm: {
        cat_name: "",
        cat_pid: 0,
        cat_level: 0,
      },
      // 编辑表单
      editForm: {
        cat_id: "",
        cat_name: "",
      },

      addCateFormRules: {
        //验证规则
        cat_name: [
          { required: true, message: "请输入分类名称", trigger: "blur" },
        ],
      },
      // 存储父级的数据
      parentCateList: [],
      selectedKeys: "", //保存用户选择分类值

      cascaderProps: {
        //配置级联菜单中数据如何展示
        value: "cat_id",
        label: "cat_name",
        children: "children",
        expandTrigger: "hover",
      },
    };
  },
  // Vue实例创建完成以后执行 数据可用
  created() {
    this.getcateList();
  },
  // Vue模板挂载完毕以后执行  DOM节点加载完毕了（可以获取节点了）
  mounted() {},
  // keepalive 缓存进入执行
  activited() {},
  // vue组件更新完毕以后执行
  update() {},
  // 定义事件
  methods: {
    async getcateList() {
      let res = await this.$axios.get("categories", { params: this.cateInfo });

      let { meta, data } = res.data;
      //  console.log(meta, data)
      if (meta.status == 200) {
        this.cateList = data.result;
        this.total = data.total;
        console.log(this.cateList);
      }
    },
    async addclassification() {
      let res = await this.$axios.get("categories", { params: { type: 2 } }); //获取父级的数据列表
      let { meta, data } = res.data;
      // console.log(meta,data)
      if (meta.status == 200) {
        this.parentCateList = data;
        console.log(this.parentCateList);
      }
      this.dialogVisible = true;
    },
    parentCateChange() {
      console.log(this.selectedKeys);
      if (this.selectedKeys.length > 0) {
        this.classificationForm.cat_pid = this.selectedKeys[
          this.selectedKeys.length - 1
        ];
        this.classificationForm.cat_level = this.selectedKeys.length;
        return;
      } else {
        this.classificationForm.cat_pid = 0;
        this.classificationForm.cat_level = 0;
      }
    },
    //添加分类
    addCate() {
      // console.log(this.classificationForm)
      this.$refs.classificationForm.validate(async (valid) => {
        if (!valid) return;
        let res = await this.$axios.post("categories", this.classificationForm);
        console.log(res);
        let { meta } = res.data;
        if (meta.status == 201) {
          this.$message.success("分类添加成功");
          this.dialogVisible = false;
          this.getcateList();
        } else {
          this.$message.error("添加分类失败");
        }
      });
    },
    // 分页器
    handleSizeChange(val) {
      // console.log(`每页 ${val} 条`);
      this.cateInfo.pagesize = val;
      this.getcateList();
    },
    handleCurrentChange(val) {
      // console.log(`当前页: ${val}`);
      this.cateInfo.pagenum = val;
      this.getcateList();
    },
    // 删除分类
    delCate(item) {
      //   // console.log(res);

      this.$confirm("此操作将永久删除该数据, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          let res = await this.$axios.delete(`categories/${item.cat_id}`);
          let { meta } = res.data;
          if (meta.status == 200) {
            this.getcateList();
            this.$message({
              type: "success",
              message: "删除成功!",
            });
          } else {
            this.$message.error(meta.msg);
          }
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    addCateDialogClosed() {
      //当关闭添加分类对话框时，重置表单
      this.$refs.classificationForm.resetFields();
      this.selectedKeys = [];
      this.classificationForm.cat_pid = 0;
      this.classificationForm.cat_level = 0;
    },
    // 编辑
    editCate(item) {
      console.log(item);
      this.editForm = item;
      this.editdialogVisible = true;
      this.getcateList();
    },
    async editCatr1(id) {
      let res = await this.$axios.put(`categories/${id}`, this.editForm);
      console.log(res);
      let { meta } = res.data;
      if (meta.status == 200) {
        this.$message.success(meta.msg);
        this.getcateList();
        this.editdialogVisible = false;
      } else {
        this.$message.error(meta.msg);
      }
    },
  },
  // 过滤器
  filter: {},
  // 计算属性
  computed: {},
  // 监听属性
  watch: {},
};
</script>

<style scoped></style>
